package com.mop.app.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class TokenService {

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 缓存token
     * @param phone
     * @param userId
     * @param token
     */
    public void cacheToken(String phone, String userId, String token) {
        JSONObject userInfo = new JSONObject();
        userInfo.put("phone", phone);
        userInfo.put(userId, userId);

        redisTemplate.opsForValue().set(token, userInfo);
    }

    /**
     * 缓存token (可用于单点)
     * @param phone
     * @param userId
     * @param token
     */
    public void cacheUserToken(String phone, String userId, String token) {
        JSONObject userInfo = new JSONObject();
        userInfo.put("phone", phone);
        userInfo.put("userId", userId);
        userInfo.put("token", token);

        redisTemplate.opsForHash().putAll(phone, userInfo);
    }

    /**
     * 获取缓存
     * @param token
     * @return
     */
    public JSONObject getCacheToken(String token) {
        Object cacheObj = redisTemplate.opsForValue().get(token);
        return cacheObj == null ? null : JSONObject.parseObject(JSONObject.toJSONString(token));
    }

    /**
     * 移除token
     * @param token
     */
    public void removeToken(String token) {
        redisTemplate.delete(token);
    }
}
